package com.lagou.edu.filter;

import com.lagou.edu.service.IUserServiceFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author stevejson
 */
@Component
@Slf4j
public class LoginFilter implements GlobalFilter, Ordered {
    @Resource
    private IUserServiceFeignClient userServiceFeignClient;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 从上下⽂中取出request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求地址
        String path=request.getPath().toString();
        if(path.startsWith("/api/user")||path.startsWith("/api/code")){
            // 合法请求，放⾏，执⾏后续的过滤器
            return chain.filter(exchange);
        }else{
            MultiValueMap<String, HttpCookie> cookies= request.getCookies();
            String token="";
            if(cookies.containsKey("token")){
                token = Objects.requireNonNull(cookies.getFirst("token")).getValue();
                if (!StringUtils.isEmpty(token)) {
                    //远程验证
                    String email= userServiceFeignClient.info(token);
                    if(!StringUtils.isEmpty(email)){
                        // 合法请求，放⾏，执⾏后续的过滤器
                        return chain.filter(exchange);
                    }
                }
            }
            log.info( "token is empty..." );
            response.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
            response.getHeaders().add("Location", "/static/login.html");
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
